<?php

namespace app\api\controller\common;

use think\Controller;
use think\Model;
use app\api\model\Role as RoleModel;
use app\api\model\Admin as AdminModel;
use app\api\model\Auth as AuthModel;
use app\api\controller\common\Commonhp;
use app\api\controller\common\CommonPlus;

class AuthorCon extends Controller {
    private $code = null;
    private $access_token = null;
    private $user_info = null;
    private $referer = null; 

    // 子类 存 则 no 
    public function _initialize(){
//        var_dump( $_SESSION);die;
//        $redirectUrl='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
//
//        if (!isset($session['user_info'])) {
//           // $this->referer = $_SESSION['REQUEST_URI'];
//             $this->getCode($redirectUrl); //sun zhushi
//        }

//        $openid=$_SESSION['user_info']['openid'];
//
//        $Model = new Model();
//        $userL = $Model->query("select * from house_user where openid='$openid'");
//        if($userL[0]["telephone"]!=""){
//            //session('user',$userL[0]["telephone"]);
//            session('user',$userL);
//        }

    }
    public function getCode1($redirectUrl){
        var_dump("denglejiance");die;
    }

    public function getCode($redirectUrl){
        //$code = I('get.code');
      $code = input('get.code');         
      //$code = $this->request->param('code');
        
        if ($code) {
            $this->code = $code;
            $this->getAccess_Token();
        } else {
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . __APPID__ . "&redirect_uri=" . $redirectUrl . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            //var_dump( $url);die;
            header("Location:$url");
            exit;
        }
    }
    public function getAccess_Token(){
        $uri = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . __APPID__ . "&secret=" . __APPSECRET__ . "&code=" . $_GET['code'] . "&grant_type=authorization_code";
       // var_dump( $uri);die;
        $data = getHttp($uri);
  
        if ($data['access_token']) {
            $_SESSION['access_token']=$data['access_token'];
            //$session['access_token']=$data['access_token'];
            $access_token = $data['access_token'];
            $openid = $data['openid'];
            $this->getUser_Info($access_token, $openid);
        } else {
            throw new Exception('Need Access_token');
        }
    }

    private function getUser_Info($access_token, $openid){
 
        $uri = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        // Get User_info
        $data = getHttp($uri);
        if ($openid) {
            $this->user_info = $data;
            session('user_info', $data);
        } else {
            throw new Exception('unknown access token!');
        }
    }

    public function sendMessage($openid,$template_id,$url,$title,$price){

        $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".__APPID__."&secret=".__APPSECRET__);
//        var_dump($json_token);die;
        $access_token=json_decode($json_token,true);
        $access_token=$access_token[access_token];

        $template=array(
            'touser'=>$openid,
            'template_id'=>$template_id,
            'url'=>$url,
            'topcolor'=>"#7B68EE",
            'data'=>array(
                'first'=>array('value'=>urlencode($title),'color'=>"#FF0000"),
                'orderMoneySum'=>array('value'=>urlencode($price),'color'=>'#FF0000'),
                'orderProductName'=>array('value'=>urlencode('检测申请套餐'),'color'=>'#FF0000'),
                'Remark'=>array('value'=>urlencode('支付时间：'.date("Y-m-d H:i:s")),'color'=>'#FF0000'), )
        );
        $json_template=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $res=http_request($url,urldecode($json_template));
    }

    public function sendOrder($openid,$template_id,$url,$orderID,$title,$price){
        $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".__APPID__."&secret=".__APPSECRET__);

        $access_token=json_decode($json_token,true);
        $access_token=$access_token[access_token];

        $template=array(
            'touser'=>$openid,
            'template_id'=>$template_id,
            'url'=>$url,
            'topcolor'=>"#7B68EE",
            'data'=>array(
                'first'=>array('value'=>urlencode($title),'color'=>"#FF0000"),
                'orderID'=>array('value'=>urlencode($orderID),'color'=>"#FF0000"),
                'orderMoneySum'=>array('value'=>urlencode($price),'color'=>'#FF0000'),
                'backupFieldName'=>array('value'=>urlencode('订单标题：'),'color'=>'#FF0000'),
                'backupFieldData'=>array('value'=>urlencode('检测申请套餐'),'color'=>'#FF0000'),
                'remark'=>array('value'=>urlencode('提交时间：'.date("Y-m-d H:i:s")),'color'=>'#FF0000'),

                )

        );
        $json_template=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $res=http_request($url,urldecode($json_template));
    }

    public function sendBirth($openid){

        // getHttp  http_request
        $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".__APPID__."&secret=".__APPSECRET__);

        $access_token=json_decode($json_token,true);
        $access_token=$access_token['access_token'];



        $template_id="eA80w39lLSGPxjcu1UCvPXh_3Dq8qz2WwHLAToKaJgY";
//            $items=array('touser'=>$students['dad'],'uname'=>$students['s_name'],'kc_name'=>$kc_name,'kc_price'=>'('.$orderinfo['paytype_name'].')'.$orderinfo['cose'],
//                'teachername'=>$njzr['tname'],'schoolid'=>$order['schoolid'],'kcid'=>$tcourse['id']);
        $url="";// <a href='".$url."' >ces</a>
        // $url=$_W['siteroot'] . 'app/' .$this->createMobileUrl('kcinfo', array( 'schoolid' =>$params['schoolid'],'id'=>$params['kcid'] ));
        $first="恭喜你有成员下订单";
        $keyword1="测试课程";
        $keyword2="laozhang";
        $keyword3=23;
        $keyword4=date('Y-m-d');
        $keyword5="zhangsan";
        $remark="感谢你，用心服务每一位家长！\n\n不开心和有压力的时候，\n深夜睡不着的时候，\n......，\n如何调频到喜悦和平？\n我们在听什么，\n";
        //$remark.="就会构建起心里的影像，\n进而构建外在的实相。\n今晚准时收听，{$params['kc_name']},\n就是选择了一种生活方式。";

        $template=array(
            'touser'=>$openid,
            'template_id'=>$template_id,
            'url'=>$url,
            'topcolor'=>"#7B68EE",
            'data'=>array(
                'first' => array(   'value' => $first,
                    'color' => '#ff510'),
                'keyword1' => array(
                    'value' => $keyword1,
                    'color' => '#000000'
                ),
                'keyword2' => array(
                    'value' =>$keyword2,
                    'color' => '#000000'
                ),
                'keyword3' => array(
                    'value' => $keyword3,
                    'color' => '#000000'
                ),
                'keyword4' => array(
                    'value' => $keyword4,
                    'color' => '#000000'
                ),
                'keyword5' => array(
                    'value' => $keyword5,
                    'color' => '#000000'
                ),
                'remark' => array(
                    'value' => $remark ,
                    'color' => '#000000'
                ),
            )

        );
        $json_template=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $res=http_request($url,urldecode($json_template));
        var_dump($res);die;
    }


    public function getXcxToken(){
        $appid="wx480fe8b312cdb934";
        $secret="032c90617774d6e04d32e778a798cd1a";

        $appid="wx7c3d4b4c70cda90f";
        $secret="8f12797c5b454ddc2c45b3413cf5687c";

        $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret);

        $access_token=json_decode($json_token,true);
        $access_token=$access_token['access_token'];

        return $access_token;

    }

    public function sendBirthxcx($openid,$usename){

        $access_token=$this->getXcxToken();

        if(!$access_token){
            exit(json_encode(array('status'=>'0','message'=>'获取token失败','data'=>'')));
        }


        $template_id="eA80w39lLSGPxjcu1UCvPXh_3Dq8qz2WwHLAToKaJgY";
//      $items=array('touser'=>$students['dad'],'uname'=>$students['s_name'],'kc_name'=>$kc_name,'kc_price'=>'('.$orderinfo['paytype_name'].')'.$orderinfo['cose'],
//      'teachername'=>$njzr['tname'],'schoolid'=>$order['schoolid'],'kcid'=>$tcourse['id']);
        $url="";// <a href='".$url."' >ces</a>
        // $url=$_W['siteroot'] . 'app/' .$this->createMobileUrl('kcinfo', array( 'schoolid' =>$params['schoolid'],'id'=>$params['kcid'] ));
        $first="开心每一天";
        $keyword1="生日提醒";
        $keyword2=date('Y-m-d H:i:s');
        $keyword3=23;
        $keyword4=date('Y-m-d');
        $keyword5="zhangsan";
        $remark="尊敬的会员：".$usename." 你好！\n\n今天是您的生日，感谢您一路的支持，\n我们将以最大的热情投入工作，服务每一位会员\n......，\n如何调频到喜悦和平？\n我们在听什么，\n";
        //$remark.="就会构建起心里的影像，\n进而构建外在的实相。\n今晚准时收听，{$params['kc_name']},\n就是选择了一种生活方式。";

//        var_dump($remark);die;
        $template=array(
            'touser'=>$openid,
            "mp_template_msg"=>array(
                "appid"=>"wx635e079a237e55f4",
                "template_id"=>"rAdwnt63i_GEz4uap3S3FO1sPM16-ZGmwbjZFNIjaU4",
                "url"=>"",
                "miniprogram"=>array(
                         "appid"=>"wx480fe8b312cdb934",
                         "pagepath"=>""
                    ),
                'data'=>array(
                        'first' => array(
                            'value' => $first,
                            'color' => '#ff510'),
                        'keyword1' => array(
                            'value' => $keyword1,
                            'color' => '#000000'
                        ),
                        'keyword2' => array(
                            'value' =>$keyword2,
                            'color' => '#000000'
                        ),
                        'keyword3' => array(
                            'value' => $keyword3,
                            'color' => '#000000'
                        ),
                        'keyword4' => array(
                            'value' => $keyword4,
                            'color' => '#000000'
                        ),
                        'keyword5' => array(
                            'value' => $keyword5,
                            'color' => '#000000'
                        ),
                        'remark' => array(
                            'value' => $remark ,
                            'color' => '#000000'
                        ),
                    )
            ),


        );
        $json_template=json_encode($template);

//        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $url="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=".$access_token;
        $res=http_request($url,urldecode($json_template));
//        var_dump($res);die;
    }

    /**
     * @param $openid
     * @param $usename
     *
     *
     * 模板ID
    DtXCeo59ZO89yiupjS0DGOkCJk_H7nYrwkjXfDmWTZ0

    服务完成通知
    行业
    消费品 - 消费品
    详细内容
    {{first.DATA}}
    预约门店：{{keyword1.DATA}}
    预约时间：{{keyword2.DATA}}
    预约类型：{{keyword3.DATA}}
    {{remark.DATA}}
     *
     *
     */

    // 提货通知
    public function sendOrdertihuo($openid,$para){

        $access_token=$this->getXcxToken();

        if(!$access_token){
            exit(json_encode(array('status'=>'0','message'=>'获取token失败','data'=>'')));
        }

//        $para=array("store_title"=>$odinfo['store_title'],"order_num"=>$odinfo['order_num'],"subscribe_time"=>$odinfo['subscribe_time'],
//            "server_name"=>$odinfo['server_name']);


       // $template_id="eA80w39lLSGPxjcu1UCvPXh_3Dq8qz2WwHLAToKaJgY";
//      $items=array('touser'=>$students['dad'],'uname'=>$students['s_name'],'kc_name'=>$kc_name,'kc_price'=>'('.$orderinfo['paytype_name'].')'.$orderinfo['cose'],
//      'teachername'=>$njzr['tname'],'schoolid'=>$order['schoolid'],'kcid'=>$tcourse['id']);
        $url="";// <a href='".$url."' >ces</a>
        // $url=$_W['siteroot'] . 'app/' .$this->createMobileUrl('kcinfo', array( 'schoolid' =>$params['schoolid'],'id'=>$params['kcid'] ));
        $first="你好";
        $keyword1=$para['store_title']; // 门店
        $keyword2=$para['subscribe_time'];// 预约时间
        $keyword3=$para['server_name'];
        $keyword4=date('Y-m-d');
        $keyword5="zhangsan";
        $remark="尊敬的用户，你好！\n\n订单已生成，\n订单号为\n".$para['order_num'];
        //$remark.="就会构建起心里的影像，\n进而构建外在的实相。\n今晚准时收听，{$params['kc_name']},\n就是选择了一种生活方式。";

//        var_dump($remark);die;
        $template=array(
            'touser'=>$openid,
            "mp_template_msg"=>array(
                "appid"=>"wx635e079a237e55f4",
                "template_id"=>"DtXCeo59ZO89yiupjS0DGOkCJk_H7nYrwkjXfDmWTZ0",
                "url"=>"",
                "miniprogram"=>array(
                    "appid"=>"wx7c3d4b4c70cda90f",// wx7c3d4b4c70cda90f  v1 wx480fe8b312cdb934
                    "pagepath"=>""
                ),
                'data'=>array(
                    'first' => array(
                        'value' => $first,
                        'color' => '#ff510'),
                    'keyword1' => array(
                        'value' => $keyword1,
                        'color' => '#000000'
                    ),
                    'keyword2' => array(
                        'value' =>$keyword2,
                        'color' => '#000000'
                    ),
                    'keyword3' => array(
                        'value' => $keyword3,
                        'color' => '#000000'
                    ),
                    'keyword4' => array(
                        'value' => $keyword4,
                        'color' => '#000000'
                    ),
                    'keyword5' => array(
                        'value' => $keyword5,
                        'color' => '#000000'
                    ),
                    'remark' => array(
                        'value' => $remark ,
                        'color' => '#000000'
                    ),
                )
            ),


        );
        $json_template=json_encode($template);

//        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $url="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=".$access_token;
        $res=http_request($url,urldecode($json_template));
        $res=json_decode($res,true);
        // errmsg
        return $res;
//        if($res['errcode']>0){
//            return $res;
//        }else{
//
//        }
//        var_dump($res);die;
    }


}